package edu.sctu;


import edu.sctu.User;
import edu.sctu.UserDao;
import edu.sctu.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;

/**
 * 注册Servlet
 */
public class RegisterServlet extends HttpServlet {

    DbUtil dbUtil = new DbUtil();
    UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");


        //用户注册表单的参数
        String userName = request.getParameter("username");
        String password = request.getParameter("password");

        Connection connection = null;
        try {
            connection=dbUtil.getCon();
            User user = new User(userName,password);//用户表单数据

            //判断用户名是否存在
            boolean isExist = userDao.isExist(connection,user);
            if (isExist){
                userDao.register(connection,user);//注册
                System.out.println("注册成功");
                response.sendRedirect("login.jsp");//注册成功后跳转到登录页面
            }else {
                request.setAttribute("error","用户名已存在！");
                request.getRequestDispatcher("register.jsp").forward(request,response);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //数据库关闭
                dbUtil.closeCon(connection);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }
}